/**
 * @description 接口-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const fs = require('fs')
const ox = require('@daelui/oxjs')
const Service = require('./service.js')
const { filer } = require('@daelui/oxkit')

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 服务
    this.$service = new Service(args)
  }

  /**
   * @function 增删改事件触发
  */
  emit (name, action, res) {
    super.emit(name, action, res)
    res = res || {}
    if (res.success) {
      this.syncPluginsCode()
    }
  }

  /**
   * @function 同步插件编码
  */
  syncPluginsCode () {
    this.$service.queryAll({
      params: {
        status: '1'
      },
      excute: {
        sort: [
          {field: 'createTime', by: 'desc'},
          {field: 'order', by: 'desc'}
        ]
      }
    }).then(res => {
      let list = res.data
      list = Array.isArray(list) ? list : []
      // 只取出启用的
      list = list.filter(item => {
        return String(item.status) === '1'
      }).map(item => {
        return `try {
  ${item.executorCompiled};
  if (typeof exports === 'function') {
    exports()
  } else if (exports && typeof exports.default === 'function') {
    exports.default()
  }
} catch (e) {}`
      })
      let content = `(function(){
var module = window.module || {}
var exports = window.exports || {}
${list.join('\n\n')}
})()
`
      let path = global.CONFIG.constant.pluginsPath
      // 文件不存在
      let dir = path.replace(/\/\w+\.js/, '')
      if (!fs.existsSync(dir)) {
        filer.buildPath(dir)
      }
      // 文件写入
      try {
        fs.writeFileSync(
          path, content
        )
      } catch (e) {}
    })
  }
}

module.exports = Controller